<script setup>
import {
    Edit,
    Delete,
    Close
} from '@element-plus/icons-vue'


import { ref } from 'vue'

const resourceTypes = ref([
  {
    "id": 0,
    "resourceValue": "免费",
  },
  {
    "id": 1,
    "resourceValue": "星星购买",
  } ,
  {
    "id": 2,
    "resourceValue": "会员购买",
  }

])
const memberTypes = ref([
    {
        "id": 1,
        "contentValue": "月会员",
    },
    {
        "id": 2,
        "contentValue": "半年会员",
    },
  {
    "id": 3,
    "contentValue": "年会员",
  },
])

const type = ref('')

const memberType = ref('')



const dataList = ref([


])




import {versionSeasonListService ,versionSeaonAddService,versionSeasonService} from '@/api/versionSeason.js'



import { Plus } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
//控制抽屉是否显示
const visibleDrawer = ref(false)
//添加表单数据模型
const dataModel = ref({

})


//导入token
import { useTokenStore } from '@/stores/token.js';
const tokenStore = useTokenStore();
const queryTime = ref([])


//上传成功的回调函数
const uploadSuccess = (result) => {
  dataModel.value.imgUrl = result.data;
    console.log(result.data);
}

const uploadAudioSuccess = (result) => {
  dataModel.value.audioUrl = result.data;
    console.log(result.data);
}

const delFile = () => {
  dataModel.value.fileUrl = '';
  dataModel.value.fileName = '';
}

//添加文章
import {ElMessage, ElMessageBox} from 'element-plus'

import {treeHoleDelService} from "@/api/treeHole.js";
import {interestTopInterestPublishService} from "@/api/interestPublishRecordData.js";
import {
  lotteryAddService,
  lotteryDelService,
  lotteryEditService,
  lotteryPublishService
} from "@/api/lottery.js";
import {
  treeAddService,
  treeDelService,
  treeEditService,
  treeListService,
  treeResourcePublishService
} from "@/api/tree.js";
import {worldMessageResourcePublishService} from "@/api/worldMessage.js";
const addData = async (clickState) => {
    //把发布状态赋值给数据模型
    dataModel.value.state = clickState;

    //调用接口
    let result = await treeAddService(dataModel.value);

    ElMessage.success(result.msg ? result.msg : '添加成功');

    //让抽屉消失
    visibleDrawer.value = false;

    //刷新当前列表
  selectDataList()
}
const uploadBackgroundUrlSuccess = (result) => {
  dataModel.value.backgroundUrl = result.data.fileUrl;
}

const delBackgroundUrl = () => {
  dataModel.value.backgroundUrl = '';
}


//上传成功的回调函数
const uploadHeadPicSuccess = (result) => {
  dataModel.value.fileUrl = result.data.fileUrl;
  dataModel.value.fileName = result.data.fileName;
}

//编辑分类
const updateData = async () => {
    //调用接口
    let result = await treeEditService(dataModel.value);

    ElMessage.success(result.msg ? result.msg : '修改成功')

    //调用获取所有分类的函数
  selectDataList();

    //隐藏弹窗
    visibleDrawer.value = false;
}
type.value=1;


//获取文章列表数据
const selectDataList = async () => {
    let params = {

      timeFrom: queryTime.value ? queryTime.value[0] : null,
      timeEnd: queryTime.value ? queryTime.value[1] : null,
    }

    let result = await treeListService(params);
   dataList.value = result.data;

}


selectDataList();



//定义变量,控制标题的展示
const title = ref('')
const showData = (row) => {
    
  visibleDrawer.value = true, title.value = '编辑生命之树'
  dataModel.value.type = row.type;
  dataModel.value.fromType = row.fromType;
  dataModel.value.name = row.name;
  dataModel.value.starNum = row.starNum;

  dataModel.value.memberType = row.memberType;

  dataModel.value.speed = row.speed;
  dataModel.value.energy = row.energy;
  dataModel.value.oreIncome = row.oreIncome;
  dataModel.value.flyTime = row.flyTime;
  dataModel.value.fileUrl = row.fileUrl;
  dataModel.value.fileName = row.fileName;
  dataModel.value.sort=row.sort;
  dataModel.value.id = row.id;


}
const delData = (row) => {
  //提示用户  确认框

  ElMessageBox.confirm(
      '你确认要删除该生命之树吗?',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        //调用接口
        let result = await treeDelService(row.id);
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        //刷新列表
        selectDataList();
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '用户取消了删除',
        })
      })
}
//清空模型的数据
const clearData = () => {

  dataModel.value.type = '';
  dataModel.value.num = '';
  dataModel.value.name = '';
  dataModel.value.id = '';
  dataModel.value.fromType ='';
  dataModel.value.starNum = '';

  dataModel.value.memberType = '';


  dataModel.value.speed = '';
  dataModel.value.energy = '';
  dataModel.value.oreIncome = '';
  dataModel.value.flyTime = '';
  dataModel.value.fileUrl = '';
  dataModel.value.fileName = '';
  dataModel.value.sort='';
}

const handleChange = (value) => {
   if(dataModel.value.type ==1){
     dataModel.value.name = "第"+value+"版本";
     dataModel.value.simpleName = 'g'+value;
   }else{
     dataModel.value.name = "第"+value+"赛事";
     dataModel.value.simpleName = 's'+value;
   }
}
const publish = async () => {

  if (select.length === 0) {
    ElMessage.error("请选择要发布的资源内容")
    return
  }
  let ids = []
  select.forEach(element => {
    ids.push(element.id)
  });
  let params = {
    ids: ids
  }
  let result = await treeResourcePublishService(params);

  selectDataList();

}
let select = []
const handleSelectionChange = (val) => {
  select = val;
}

const selected = (row, index) => {
  return dataList.value[index].publishState == 0
}

</script>
<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>生命之树管理</span>
                <div class="extra">
                    <el-button type="primary" @click="visibleDrawer = true; title = '添加生命之树'; clearData()">添加生命之树</el-button>
                </div>
            </div>
        </template>
        <!-- 搜索表单 -->
      <el-form inline>
        <el-button type="primary" @click="publish">发布</el-button>
      </el-form>
        <!-- 文章列表 -->
        <el-table :data="dataList" border  style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" :selectable="selected"/>

          <el-table-column label="生命之树名称" prop="name" width="150"></el-table-column>
          <el-table-column label="排序（从小到大）" prop="sort" width="150"></el-table-column>
          <el-table-column label="获取方式"  width="100" >
            <template v-slot="scope">
              <span v-if="scope.row.fromType==0">免费</span>
              <span v-if="scope.row.fromType==1">星星购买</span>
              <span v-if="scope.row.fromType==2">会员获得</span>
              <span v-else ></span>
            </template>
          </el-table-column>
           <el-table-column label="所需星星数量" prop="starNum"  width="150"></el-table-column>
          <el-table-column label="所需会员类型"   width="120">
            <template v-slot="scope">
              <span v-if="scope.row.memberType==0">普通用户</span>
              <span v-if="scope.row.memberType==1">月会员</span>
              <span v-if="scope.row.memberType==2">半年会员</span>
              <span v-if="scope.row.memberType==3">年会员</span>
              <span v-else ></span>
            </template>
          </el-table-column>


          <el-table-column label="背景图片" width="150">
            <template v-slot="scope">
              <img v-if="scope.row.fileUrl" :src="scope.row.fileUrl" width="40" height="40" class="head_pic" />
            </template>
          </el-table-column>
          <el-table-column label="发布状态"   width="100">
            <template v-slot="scope">
              <span v-if="scope.row.publishState==0">未发布</span>
              <span v-if="scope.row.publishState==1">已发布</span>
              <span v-else ></span>
            </template>
          </el-table-column>
            <el-table-column label="创建时间" width="200px" prop="createTime"></el-table-column>

            <el-table-column label="操作"  width="150px">
                <template #default="{ row }">
                    <el-button :icon="Edit" circle plain type="primary" @click="showData(row)"></el-button>
                  <el-button :icon="Delete" circle plain type="danger" @click="delData(row)"></el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>




        <!-- 抽屉 -->
        <el-drawer v-model="visibleDrawer" :title="title" direction="rtl" size="50%">
            <!-- 添加文章表单 -->
            <el-form :model="dataModel" label-width="200px">

              <el-form-item label="生命之树名称">
                <el-input v-model="dataModel.name" type="text" style="width: 210px;"/>
              </el-form-item>
              <el-form-item label="排序">
                <el-input-number v-model="dataModel.sort" />
              </el-form-item>

              <el-form-item label="获取方式">
                <el-select placeholder="请选择" v-model="dataModel.fromType">
                  <el-option v-for="c in resourceTypes" :key="c.id" :label="c.resourceValue" :value="c.id">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="会员类型" v-if="dataModel.fromType ===2">
                <el-select placeholder="请选择"   v-model="dataModel.memberType">
                  <el-option v-for="c in memberTypes" :key="c.id" :label="c.contentValue" :value="c.id">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="星星数量" v-if="dataModel.fromType ===1" >
                <el-input-number :min="0" v-model="dataModel.starNum" />
              </el-form-item>




              <el-form-item label="生命之树图片" >
                <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false"
                           action="/api/admin/upload/uploadFile/v2" name="file"
                           :headers="{ 'Authorization': tokenStore.token }"
                           :on-success="uploadHeadPicSuccess">
                  <img v-if="dataModel.fileUrl" :src="dataModel.fileUrl" class="avatar"/>
                  <el-icon v-else class="avatar-uploader-icon">
                    <Plus/>
                  </el-icon>
                </el-upload>
                <span v-if="show">{{ dataModel.fileUrl }}</span>
                <el-icon v-if="dataModel.fileUrl" @click="delFile()">
                  <Close/>
                </el-icon>
              </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="title == '添加生命之树' ? addData() : updateData()">保存</el-button>

                </el-form-item>
            </el-form>
        </el-drawer>


    </el-card>
</template>
<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}


/* 抽屉样式 */
.avatar-uploader {
    :deep() {
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }
    }
}

.editor {
    width: 100%;

    :deep(.ql-editor) {
        min-height: 200px;
    }
}
</style>